<script setup>
import {onMounted, ref, nextTick, h} from 'vue';
import TheIcon from '@/components/icon/TheIcon.vue'
import api from '@/api'
import {NButton, NFlex, NForm, NFormItem, NInput, NSelect, NTag, useMessage} from "naive-ui";
import Appointment from './appointment.vue';
import {useCRUD} from "@/composables";
import {renderIcon} from "@/utils";
import Add from "./add.vue";
import DoctorSchedule from "./DoctorSchedule.vue";

const base_path = import.meta.env.VITE_BASE
const message = useMessage()

const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '预约',
  initForm: {},
  doCreate: api.createAppointment,
  doDelete: api.deleteAppointment,
  doUpdate: api.updateAppointment,
  refresh: () => on_ref(),
})

const data = reactive({
  show_todo:false,
  todo_loading:true,
  card_loading:false,
  todo_list:[],
  start_time:"",
  end_time:"",
  meeting_users:[],
  projects:[],
  search_loading:false,
  appointments:[],
  customers:[],
  select_customers:[],
  nums:{
    arrive_num:0,
    cancel_num:0,
    all_num:0
  },
  show_calendar:false,
  appoint_counts:[],
  calendar_date:"",
  calendar_loading:false,
  doctors:[], // 当天有排班的医生（用于预约界面）
  allDoctors:[], // 所有医生（用于排班界面）
  advisers:[],
  rooms:[],
  departments:[],
  devices:[],
  show_add:false,
  show_schedule:false
});

onMounted(() => {
  // 获取当前时间
  const today = new Date();
  // 明天作为未来7天的起始日
  const startDate = new Date(today);
  data.start_time = today.toLocaleDateString('en-CA');
  startDate.setDate(today.getDate() + 0);  // +1 代表从明天开始算
  // 未来7天的结束日（6天后）
  const endDate = new Date(today);
  endDate.setDate(today.getDate() + 7);    // +7 表示7天后

  data.end_time = endDate.toISOString().split('T')[0]
  data.calendar_date = startDate.toISOString().split('T')[0]
  get_config()
  get_devices()
  on_ref()
});

function on_ref() {
  get_appointments()
  data.show_add = false
}

function get_devices() {
  api.getDeviceList().then((res) => {
    data.devices = res.data
  })
}

function get_config() {
  api.getConfig().then((res) => {
    data.departments = res.data.deps
    data.rooms = res.data.rooms
  })
  
  // 获取所有医生
  api.getUserList({
    type:2
  }).then((res) => {
    const allDoctors = res.data
    // 获取当天有排班的医生
    getScheduledDoctors(allDoctors)
  })
  
  api.getUserList({
    type:3
  }).then((res) => {
    data.advisers = res.data
  })
}

// 获取当天有排班的医生
function getScheduledDoctors(allDoctors) {
  // 保存所有医生
  data.allDoctors = allDoctors
  
  const today = new Date()
  const year = today.getFullYear()
  const month = today.getMonth() + 1
  
  api.getDoctorSchedules({
    year: year,
    month: month
  }).then((res) => {
    const schedules = res.data || []
    
    // 获取今天有排班的医生ID
    const todayStr = today.toISOString().split('T')[0] // 格式: YYYY-MM-DD
    const scheduledDoctorIds = new Set()
    
    schedules.forEach(schedule => {
      const scheduleDate = schedule.date.split('T')[0] // 提取日期部分
      if (scheduleDate === todayStr && schedule.is_scheduled) {
        scheduledDoctorIds.add(schedule.doctor_id)
      }
    })
    
    // 过滤出今天有排班的医生（用于预约界面）
    data.doctors = allDoctors.filter(doctor => scheduledDoctorIds.has(doctor.id))
    
    console.log('Today scheduled doctors:', data.doctors)
  }).catch((error) => {
    console.error('Failed to get scheduled doctors:', error)
    // 如果获取排班失败，显示所有医生
    data.doctors = allDoctors
  })
}

function search_customer(query){
  data.search_loading = true
  api.getCustomers({keyword:query}).then((res) => {
     data.select_customers = res.data.items
     data.search_loading = false
  })
}

// 更新预约
const updateAppointments = (newAppointments) => {
  data.appointments = newAppointments;
};

// 删除预约
const handleDeleteAppointment = (id) => {
    on_ref()
};

function get_appointments(){
   data.card_loading = true
   api.getAppointment({
    date:data.start_time,
    workbench:1,
  }).then((res) => {
     data.customers = res.data.customers
     data.appointments = res.data.items
     data.nums = res.data.nums
     data.card_loading = false
  })
}

function add_appointment(){
  data.show_add = true
}

function search_project(query){
  data.search_loading = true
  api.getProjects({keyword:query}).then((res) => {
     data.projects = res.data.list
     data.search_loading = false
  })
}

function save_appointment(){
  handleSave()
}
function show_calendar(){
  data.calendar_loading = true
  api.countAppointment({
    date:data.calendar_date,
  }).then((res) => {
     data.appoint_counts = res.data
     data.show_calendar = true
     data.calendar_loading = false
  })
}

function select_date(year, month, date){
   data.show_calendar = false
   message.success(`进入${year}年${month}月${date}日的所有预约`)
   data.start_time = year+"-"+month+"-"+date
   get_appointments()
}

// function handleUpdateValue(_, { year, month, date }) {
//   message.success(`${year}-${month}-${date}`)
// }
function change_month({ year, month }){
  message.success(`当前显示的月份是: ${year}年${month}月`)
  data.calendar_date = year+"-"+month
  show_calendar()
}

function handleBeforeLeave(){

}

function show_doctor_schedule(){
  data.show_schedule = true
}

// 刷新医生列表（当排班状态改变时调用）
function refreshDoctorsList() {
  api.getUserList({
    type:2
  }).then((res) => {
    const allDoctors = res.data
    getScheduledDoctors(allDoctors)
  })
}

const getCountForDate = (year, month, day) => {
  const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  const found = data.appoint_counts.find(item => item.date === formattedDate);
  if(found){
    if(found.count===0){
      return "";
    }else{
      return "当日:"+found.count+"个";
    }
  }else{
    if(data.calendar_loading === false){
      return "切换该月份";
    }else{
      return "";
    }

  }
};
</script>

<template>
  <n-spin :show="data.card_loading" style="height: 100%;">
    <n-tabs type="segment" animated style="margin-top: 70px;width: 100%;">
      <n-tab-pane name="doctor" tab="医生" @before-leave="get_appointments()">
        <Appointment :customers="data.doctors" @call-parent="on_ref"
        :appointments="data.appointments" app_type="doctor_id"
        @update:appointments="updateAppointments"
        @delete-appointment="handleDeleteAppointment"/>
        
      </n-tab-pane>
      <n-tab-pane name="adviser" tab="顾问" @before-leave="get_appointments()">
        <Appointment :customers="data.advisers" @call-parent="on_ref"
        :appointments="data.appointments" app_type="adviser_id"
        @update:appointments="updateAppointments"
        @delete-appointment="handleDeleteAppointment"/>
      </n-tab-pane>
<!--      <n-tab-pane name="department" tab="科室" @before-leave="get_appointments()">-->
<!--        <Appointment :customers="data.departments" @call-parent="on_ref"-->
<!--        :appointments="data.appointments" app_type="department_id"-->
<!--        @update:appointments="updateAppointments"-->
<!--        @delete-appointment="handleDeleteAppointment"/>-->
<!--      </n-tab-pane>-->
      <n-tab-pane name="room" tab="诊室" @before-leave="get_appointments()">
        <Appointment :customers="data.rooms" @call-parent="on_ref"
        :appointments="data.appointments" app_type="room_id"
        @update:appointments="updateAppointments"
        @delete-appointment="handleDeleteAppointment"/>
      </n-tab-pane>
      <n-tab-pane name="device" tab="仪器" @before-leave="get_appointments()">
        <Appointment :customers="data.devices" @call-parent="on_ref"
        :appointments="data.appointments" app_type="device_id"
        @update:appointments="updateAppointments"
        @delete-appointment="handleDeleteAppointment"/>
      </n-tab-pane>
    </n-tabs>
  </n-spin>

  <div class="tools">
    <div style="display: flex;align-items: center">
      <div class="item">
        <div style="background: #8945c3" class="tag">&nbsp;</div>
        <div class="tag_value">总预约&nbsp;|&nbsp;{{data.nums.all_num}}人</div>
      </div>

      <div class="item">
        <div style="" class="tag">&nbsp;</div>
        <div class="tag_value">已到店&nbsp;|&nbsp;{{data.nums.arrive_num}}人</div>
      </div>

      <div class="item">
        <div style="background: #d95b74" class="tag">&nbsp;</div>
        <div class="tag_value">已爽约&nbsp;|&nbsp;{{data.nums.cancel_num}}人</div>
      </div>
    </div>

    <div style="display: flex;">
        <NButton type="primary" :loading="data.card_loading" secondary @click="on_ref" style="margin-right: 5px">刷新</NButton>
        <NButton type="primary" secondary @click="add_appointment" style="margin-right: 5px"><TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建预约</NButton>
        <NButton type="info" secondary @click="show_doctor_schedule" style="margin-right: 5px">
          <TheIcon icon="material-symbols:schedule" :size="18" class="mr-5" />医生排班
        </NButton>
        <NButton type="primary"  @click="show_calendar" circle >
          <component :is="renderIcon('material-symbols-light:event-available-outline-rounded', { size: 25,color:'#fff' })" />
        </NButton>
    </div>

  </div>
  
  <n-drawer v-model:show="data.show_add" width="80%">
        <Add  @call-parent="on_ref"/>
    </n-drawer>

  <!-- 医生排班抽屉 -->
  <DoctorSchedule 
    v-model:show="data.show_schedule"
    :doctors="data.allDoctors"
    @schedule-changed="refreshDoctorsList"
  />

 <n-modal
    v-model:show="data.show_calendar"
    class="custom-card"
    preset="card"
    title="日历模式"
    size="huge"
    :bordered="false"
    style="width: 1000px"
  >
    <n-spin :show="data.calendar_loading" style="--n-opacity-spinning:0.1;height: 100%;">
    <n-calendar
    v-model:value="value"
    #="{ year, month, date }"
    :is-date-disabled="isDateDisabled"
    @update:value="handleUpdateValue"
    :on-panel-change="change_month"
    >
    <div style="width: 100px;height:50px;text-align: center;padding-top:20px">
      {{ getCountForDate(year, month, date) }}
      <n-button size="tiny" @click="select_date(year, month, date)" type="error" v-if="getCountForDate(year, month, date)&&getCountForDate(year, month, date)!=='切换该月份'">查看详情</n-button>
    </div>

  </n-calendar>
    </n-spin>

  </n-modal>



</template>
<style scoped>
.tools{
  position: fixed;
  width: calc(100% - 100px);
  height:60px;
  background: #f5f5f5;
  bottom:0;
  z-index: 10;
  display: flex;
  align-items: center;
  padding: 0 30px;
  justify-content: space-between;
}
.item{
  display: flex;
  align-items: center;
  margin-right: 20px;
  .tag{
    width: 10px;
    height:5px;
    background: green;
  }
  .tag_value{
    font-size: 14px;
    color:#6a6a6a;
    margin-left: 5px;
  }
}

</style>

